package de.tudarmstadt.ukp.wikisniffer.userstudy.datastore;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import de.tudarmstadt.ukp.wikisniffer.userstudy.Client;

public class ResultStore {
	
	private File resultFile;
	private boolean isCounting = false;
	private Task currentTask;
	public enum Task {QUESTION, INFO};
	public enum Action {STARTED, ENDED, TIMER, INFO};
	
	public void init(String filePath){
		resultFile = new File(filePath);
	}
	
	public void startTask(Task task, String question) throws IOException{
		if(isCounting) System.out.println("Already doing a task!");
		isCounting = true;
		currentTask = task;
		saveAction(Action.STARTED.name() + "\t" + task.name() + "\t" + question);
		
	}
	
	public void stopTask(Object result) throws IOException{
		if(!isCounting){
			saveAction(Action.INFO + "\t" + Task.INFO + "\t" + result.toString());
			return;
		}
		isCounting = false;
		saveAction(Action.ENDED.name() + "\t" + currentTask.name() + "\t" + result.toString());
		currentTask = null;		
	}
	
	public void saveAction(String output) throws IOException{
		
		output += "\t";
		output += new Date().getTime();
		appendTextToFile(output);
		
	}
	
	private void appendTextToFile(String line) throws IOException{
		BufferedWriter appender = new BufferedWriter(new FileWriter(resultFile, true));
		appender.write("\n");
		appender.write(line);
		appender.close();		
	}

	public void notifyPossibleStop(String event) {
		try {
			saveAction(Action.TIMER.name() + "\t" + currentTask.name() + "\t" + event);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	public void setVPCode(String answer) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(resultFile));
		
		File oldResultFile = resultFile;

		resultFile = new File("results/" + answer + ".dat");
		BufferedWriter appender = new BufferedWriter(new FileWriter(resultFile, true));
		saveAction("VP-Code: " + answer);
		Client.vpCode = answer;
		String line;
		while( (line = reader.readLine()) != null)
		{
			appender.write("\n");
			appender.write(line);
		}
		appender.close();		
		reader.close();
		
		oldResultFile.delete();
		
	}

}
